package cmd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"litter-api/app/conf"
)

var (
	cfgFile string
	rootCmd = &cobra.Command{
		Use:   "litter run [flags] [value]",
		Short: "litter run",
		Long: ` ___       ___  _________  _________  _______   ________     
|\  \     |\  \|\___   ___\\___   ___\\  ___ \ |\   __  \    
\ \  \    \ \  \|___ \  \_\|___ \  \_\ \   __/|\ \  \|\  \   
 \ \  \    \ \  \   \ \  \     \ \  \ \ \  \_|/_\ \   _  _\  
  \ \  \____\ \  \   \ \  \     \ \  \ \ \  \_|\ \ \  \\  \| 
   \ \_______\ \__\   \ \__\     \ \__\ \ \_______\ \__\\ _\ 
    \|_______|\|__|    \|__|      \|__|  \|_______|\|__|\|__|`,
		Version: "v0.0.1",
	}
	cfg            *conf.Config
	logrusLevelMap = map[string]logrus.Level{
		"panic": logrus.PanicLevel,
		"fatal": logrus.FatalLevel,
		"error": logrus.ErrorLevel,
		"warn":  logrus.WarnLevel,
		"info":  logrus.InfoLevel,
		"debug": logrus.DebugLevel,
		"trace": logrus.TraceLevel,
	}
)

func Execute() error {
	return rootCmd.Execute()
}

func init() {
	cobra.OnInitialize(initialize)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.litter.yml)")
}

func initialize() {
	var (
		lv  logrus.Level
		ok  bool
		err error
	)
	fmt.Println(rootCmd.Long)
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})

	conf.Initialize(cfgFile)
	logrus.WithFields(logrus.Fields{"method": "Initialize"}).Info("Custom configuration file: ", cfgFile)

	cfg, err = conf.GetConfig()
	if err != nil {
		logrus.Fatal(err)
	}
	logrus.WithFields(logrus.Fields{"method": "Initialize"}).Info("Configuration file currently in use: ", viper.ConfigFileUsed())
	//src.PrepareConfig(cfg)

	// 设置日志工具
	lv, ok = logrusLevelMap[cfg.LogLevel]
	if !ok {
		logrus.Fatal("Log level can only be one of trace, debug, info, warn, error, fatal, panic")
	}
	logrus.SetLevel(lv)

	// 设置gin
	if lv >= logrus.DebugLevel {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
}
